using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;

namespace SMSManager.Data
{
	internal class UserCollectionTypeConverter : XmlTypeConverter<UserCollection>
	{
		public override object ConvertFrom(ITypeDescriptorContext ctx, CultureInfo ci, object data)
		{
			var users = (UserCollection) base.ConvertFrom(ctx, ci, data);
			Debug.Assert(users != null, "users != null");

			if (users.UserKeys.Count != users.UserValues.Count)
			{
				throw new InvalidOperationException();
			}
			for (int i = 0; i < users.UserKeys.Count; i++)
			{
				users.Value.Add(users.UserKeys[i], users.UserValues[i]);
			}
			return users;
		}

		public override object ConvertTo(ITypeDescriptorContext ctx, CultureInfo ci, object value, Type type)
		{
			if (!(value is UserCollection))
			{
				return new InvalidCastException();
			}
			var users = (UserCollection) value;
			users.UserKeys.Clear();
			users.UserValues.Clear();
			foreach (var user in users.Value)
			{
				if (user.Value.IsRemember)
				{
					users.UserKeys.Add(user.Key);
					users.UserValues.Add(user.Value);
				}
			}
			return base.ConvertTo(ctx, ci, value, type);
		}
	}
}